<script setup>
import { ref, watch } from 'vue'

const count = ref(0)
const addCount = () => {
  count.value++
}
// watch(count, (newValue, oldValue) => {
//   console.log(oldValue)
//   console.log(newValue)
// })

// 立即监听
const age = ref(20)
const addAge = () => {
  age.value++
}

// watch(
//   [count, age],
//   (newValue, oldValue) => {
//     console.log(oldValue)
//     console.log(newValue)
//   },
//   // 立即监听: 进入或页面刷新后立即执行监听
//   {
//     immediate: true,
//   }
// )

// 深度监听
const countRef = ref({
  value: 0,
})

const addCountRef = () => {
  countRef.value.value++
}

// watch(
//   countRef,
//   (newValue, oldValue) => {
//     console.log(oldValue)
//     console.log(newValue)
//   },
//   {
//     deep: true,
//   }
// )

// 这个负载类型是监控的地址, oldValue和newValue都是同一个地址
// 解决方法: 深度克隆:JSON.stringify()和JSON.parse()
let oldState = JSON.parse(JSON.stringify(countRef.value))
watch(
  countRef,
  (newValue) => {
    console.log(oldState)
    console.log(newValue)
    oldState = JSON.parse(JSON.stringify(newValue))
  },
  {
    deep: true,
  }
)
</script>
<template>
  <div class="box">
    <button class="my-button" @click="addCount">count: {{ count }}</button>
    <button class="my-button" @click="addAge">age: {{ age }}</button>
    <button class="my-button" @click="addCountRef">
      countRef: {{ countRef.value }}
    </button>
  </div>
</template>

<style lang="scss" scoped>
.box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  padding: 20px;
}

.my-button {
  display: inline-block;
  text-align: center;
  vertical-align: middle;
  padding: 15px 32px;
  text-decoration: none;
  font-size: 16px;
  font-weight: 500;
  border-radius: 4px;
  border: none;
  cursor: pointer;

  background-color: #4caf50;
  color: white;

  transition: background-color 0.3s ease;
  &:hover {
    background-color: #45a049;
  }

  &:active {
    background-color: #388e3c;
  }
}
</style>
